import React, { useState, useEffect } from 'react';
import { Form, Button, Card, Alert, Container } from 'react-bootstrap';
import { useNavigate } from 'react-router-dom';
import AuthService from '../services/AuthService';

const Login = () => {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [loading, setLoading] = useState(false);
  const [message, setMessage] = useState('');
  const navigate = useNavigate();

  // 检测已登录状态并自动跳转
  useEffect(() => {
    const checkAuthStatus = () => {
      if (AuthService.isAuthenticated()) {
        const user = AuthService.getCurrentUser();
        console.log('登录页面检测到用户已登录:', user);

        // 处理管理员/普通用户跳转逻辑
        const isAdmin =
            (user && user.role === 'ROLE_ADMIN') ||
            (user && user.user && user.user.role === 'ROLE_ADMIN');

        navigate(isAdmin ? '/admin' : '/todos');
      }
    };

    checkAuthStatus();
  }, [navigate]);

  // 登录处理函数
  const handleLogin = (e) => {
    e.preventDefault();
    setMessage('');
    setLoading(true);

    // 表单验证
    if (!username || !password) {
      setMessage('请填写所有字段');
      setLoading(false);
      return;
    }

    // 执行登录逻辑
    AuthService.login(username, password)
        .then(response => {
          console.log('登录响应:', response);
          if (response.code === 200) {
            const user = AuthService.getCurrentUser();

            // 检查账户禁用状态
            const isDisabled =
                (user && user.enabled === false) ||
                (user && user.user && user.user.enabled === false);

            if (isDisabled) {
              console.log('账户已被禁用');
              setMessage('您的账户已被管理员禁用，请联系管理员解决');
              AuthService.logout();
              setLoading(false);
              return;
            }

            // 触发登录状态变更事件
            window.dispatchEvent(new Event('login-state-change'));

            // 跳转逻辑
            const isAdmin =
                (user && user.role === 'ROLE_ADMIN') ||
                (user && user.user && user.user.role === 'ROLE_ADMIN');

            navigate(isAdmin ? '/admin' : '/todos');
          } else {
            setMessage(response.message || '登录失败，请检查您的账号和密码');
            setLoading(false);
          }
        })
        .catch(error => {
          console.error('登录错误:', error);
          const resMessage =
              (error.response && error.response.data && error.response.data.message) ||
              error.message ||
              error.toString();

          setMessage(resMessage);
          setLoading(false);
        });
  };

  return (
      <Container className="d-flex justify-content-center align-items-center min-vh-100">
        <Card className="shadow rounded-4 p-5 w-100" style={{ maxWidth: '450px' }}>
          <Card.Body className="px-5">
            {/* 标题区域 */}
            <div className="text-center mb-5">
              <h2 className="fw-bold text-gray-800">用户登录</h2>
              <p className="text-muted mt-2">请使用注册账号登录</p>
            </div>

            {/* 错误提示 */}
            {message && (
                <Alert
                    variant="danger"
                    className="mb-4 rounded-3 shadow-sm"
                    style={{
                      backgroundColor: '#ffe6e6',
                      borderColor: '#ffcccc',
                      padding: '12px'
                    }}
                >
                  <i className="fa fa-exclamation-triangle me-2"></i>
                  {message}
                </Alert>
            )}

            {/* 登录表单 */}
            <Form onSubmit={handleLogin}>
              <Form.Group className="mb-4">
                <Form.Label className="fw-semibold text-gray-700">用户名</Form.Label>
                <Form.Control
                    type="text"
                    placeholder="请输入注册时使用的用户名"
                    value={username}
                    onChange={(e) => setUsername(e.target.value)}
                    className="rounded-3 shadow-sm"
                    style={{ height: '50px' }}
                    required
                />
              </Form.Group>

              <Form.Group className="mb-4">
                <Form.Label className="fw-semibold text-gray-700">密码</Form.Label>
                <Form.Control
                    type="password"
                    placeholder="请输入您的登录密码"
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                    className="rounded-3 shadow-sm"
                    style={{ height: '50px' }}
                    required
                />
              </Form.Group>

              <Button
                  variant="success"
                  type="submit"
                  className="w-100 py-2 fs-5 rounded-3 shadow-sm"
                  disabled={loading}
              >
                {loading ? '正在验证身份...' : '立即登录'}
              </Button>
            </Form>

            {/* 注册链接 */}
            <div className="mt-4 text-center">
              <span className="text-muted me-1">还没有账号？</span>
              <Button
                  variant="link"
                  className="text-success fw-semibold p-0"
                  onClick={() => navigate('/register')}
              >
                点击创建新账户
              </Button>
            </div>
          </Card.Body>
        </Card>
      </Container>
  );
};

export default Login;